//
//  ZCWebVC.m
//  ZCJZ
//
//  Created by sujeking on 2019/3/6.
//  Copyright © 2019年 jeking. All rights reserved.
//

#import "ZCWebVC.h"
//#import "WZGGoodsDetailVC.h"
//#import "WZGShareView.h"
//#import "WZGMoreShareVC.h"
//#import "ZCOrderPayVC.h"
@import WebKit;
#import <MBProgressHUD.h>

@interface ZCWebVC () <WKNavigationDelegate,WKUIDelegate,WKScriptMessageHandler>

@property (nonatomic, strong) WKWebView *webview;
@property (nonatomic, strong) WKWebViewConfiguration *config ;


@end

@implementation ZCWebVC

- (void)viewDidLoad {
  [super viewDidLoad];
  self.view.backgroundColor = [UIColor whiteColor];
  [self setupUI];
  if (self.localPath != nil) {
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:self.localPath]
                                             cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                         timeoutInterval:20];
    [self.webview loadRequest:request];
    return;
  }
  if (self.remotePath != nil) {
    self.remotePath = [self URLDecodedString:self.remotePath];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.remotePath]
                                             cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                         timeoutInterval:20];
    [self.webview loadRequest:request];
    
    return;
  }
  if (self.htmlstr != nil) {
    NSString *html = [NSString stringWithFormat:@"<!DOCTYPE html> <html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <title>Document</title> <style> html,body {            margin: 0;padding: 0; width: 100%%; } img { width: 100%%; } </style> </head> <body> %@</body> </html>",self.htmlstr];
    [self.webview loadHTMLString:html baseURL:nil];
    return;
  }
}

- (void)setupUI {
  dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    self.webview.frame = self.view.bounds;
    [self.view addSubview:self.webview];
  });
}

- (void)viewWillAppear:(BOOL)animated {
  [super viewWillAppear:animated];
  self.navigationController.navigationBarHidden = NO;
}


- (void)viewWillDisappear:(BOOL)animated {
  [super viewWillDisappear:animated];
  [MBProgressHUD hideHUDForView:self.view animated:YES];
}

- (void)basePopAction {
  if (self.webview.canGoBack) {
    [self.webview goBack];
  } else {
    [self.navigationController popViewControllerAnimated:YES];
  }
}

// MARK: - WKWebViewDelegate

- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
  UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
  [alertController addAction:([UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    completionHandler();
  }])];
  [self presentViewController:alertController animated:YES completion:nil];
  
}
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler{
  UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
  [alertController addAction:([UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    completionHandler(NO);
  }])];
  [alertController addAction:([UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    completionHandler(YES);
  }])];
  [self presentViewController:alertController animated:YES completion:nil];
}
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler{
  UIAlertController *alertController = [UIAlertController alertControllerWithTitle:prompt message:@"" preferredStyle:UIAlertControllerStyleAlert];
  [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
    textField.text = defaultText;
  }];
  [alertController addAction:([UIAlertAction actionWithTitle:@"完成" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    completionHandler(alertController.textFields[0].text?:@"");
  }])];
  
  [self presentViewController:alertController animated:YES completion:nil];
}

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
  //    if ([message.name isEqualToString:@"jssdk"]) {
  //        NSString *func = [message.body valueForKey:@"func"];
  //        if ([func isEqualToString:@"getUserInfoFunc"]) {
  //            [self.webview evaluateJavaScript:[NSString stringWithFormat:@"window.userInfo = %@",[self.userModel mj_JSONString]] completionHandler:^(id info, NSError * _Nullable error) {
  //            }];
  //        }
  //        if ([func isEqualToString:@"loadGoodsDetailFunc"]) {
  //            NSDictionary *dict = [message.body valueForKey:@"param"];
  //            if (dict == nil) {
  //                [self.webview evaluateJavaScript:@"alert('参数错误')" completionHandler:nil];
  //                return;
  //            }
  //            WZGGoodsDetailVC *vc = [[WZGGoodsDetailVC alloc] init];
  //            vc.idstr = [dict valueForKey:@"id"];
  //            [self.navigationController pushViewController:vc animated:YES];
  //        }
  //        if ([func isEqualToString:@"loadHomePageFunc"]) {
  //            [self.tabBarController setSelectedIndex:0];
  //            [self.navigationController popViewControllerAnimated:YES];
  //        }
  //        if ([func isEqualToString:@"loadCategoryPageFunc"]) {
  //            [self.tabBarController setSelectedIndex:1];
  //            [self.navigationController popViewControllerAnimated:YES];
  //        }
  //        if ([func isEqualToString:@"showShareViewFunc"]) {
  //            NSDictionary *dict = [message.body valueForKey:@"param"];
  //            if (dict == nil) {
  //                [self.webview evaluateJavaScript:@"alert('参数错误')" completionHandler:nil];
  //                return;
  //            }
  //            WZGMoreShareVC *vc = [[WZGMoreShareVC alloc] init];
  //            vc.goodsId = [dict valueForKey:@"id"];
  //            [vc setModalPresentationStyle:UIModalPresentationOverCurrentContext];
  //            [self.view.window.rootViewController presentViewController:vc animated:YES completion:nil];
  //        }
  //        if ([func isEqualToString:@"loadPayViewFunc"]) {
  //            ZCOrderPayVC *vc = [[ZCOrderPayVC alloc] init];
  //            NSDictionary *dict = [message.body valueForKey:@"param"];
  //            vc.order_id = [dict valueForKey:@"orderId"];
  //            [self.navigationController pushViewController:vc animated:YES];
  //        }
  //
  //        if ([func isEqualToString:@"popCurrentVCFunc"]) {
  //            NSString *jsonStr = [message.body valueForKey:@"param"];
  //            NSDictionary *dict = [jsonStr mj_JSONObject];
  //            if ([[dict valueForKey:@"QAback"] isEqualToString:@"success"]) {
  //                WeakSelf(self);
  //
  //                [self netFetchMemberInfo:^{
  //                    StrongSelf(self);
  //                    [[NSNotificationCenter defaultCenter] postNotificationName:@"loginSuccess" object:nil];
  //                    [self dismissViewControllerAnimated:YES completion:nil];
  //                }];
  //            }else{
  //                [self.navigationController popViewControllerAnimated:YES];
  //            }
  //        }
  //    }
}

- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {
  [MBProgressHUD hideHUDForView:self.view animated:YES];
  [self.view makeToast:error.description duration:2.0 position:CSToastPositionCenter];
  dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    [self.navigationController popViewControllerAnimated:YES];
  });
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {
  NSString *jssdk = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"jssdk" ofType:@"js"] encoding:NSUTF8StringEncoding error:nil];
  [self.webview evaluateJavaScript:jssdk completionHandler:nil];
  [self.webview evaluateJavaScript:@"document.documentElement.style.webkitTouchCallout='none';" completionHandler:nil];
  [self.webview evaluateJavaScript:@"document.documentElement.style.webkitUserSelect='none';"completionHandler:nil];
  dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    [MBProgressHUD hideHUDForView:self.view animated:YES];
  });
}

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
  [MBProgressHUD hideHUDForView:self.view animated:YES];
  [MBProgressHUD showHUDAddedTo:self.view animated:YES];//加载之前给h5传递用户信息
}

- (NSString *)URLEncodedString:(NSString *)str {
  NSString *encodedString = (NSString *)
  CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                            (CFStringRef)str,
                                                            NULL,
                                                            (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                            kCFStringEncodingUTF8));
  
  return encodedString;
}

- (NSString *)URLDecodedString:(NSString *)str {
  NSString *decodedString=(__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL, (__bridge CFStringRef)str, CFSTR(""), CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
  
  return decodedString;
}


- (void)setParams:(NSDictionary *)params {
  [super setParams:params];
  NSURLRequest *request = nil;
  if ([params.allKeys containsObject:@"localPath"]) {
    request = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:[params valueForKey:@"localPath"]]
        cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
    timeoutInterval:20];
    [self.webview loadRequest:request];
    return;
  }
  if ([params.allKeys containsObject:@"remotePath"]) {
    request = [NSURLRequest requestWithURL:[NSURL URLWithString:[params valueForKey:@"remotePath"]]
        cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
    timeoutInterval:20];
    [self.webview loadRequest:request];
    return;
  }
  if ([params.allKeys containsObject:@"htmlstr"]) {
    NSString *html = [NSString stringWithFormat:@"<!DOCTYPE html> <html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <title>Document</title> <style> html,body {            margin: 0;padding: 0; width: 100%%; } img { width: 100%%; } </style> </head> <body> %@</body> </html>",self.htmlstr];
    [self.webview loadHTMLString:html baseURL:nil];
    return;
  }
}

// MARK: - GET

- (WKWebView *)webview {
  if (_webview == nil) {
     WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
     WKUserContentController *userController = [[WKUserContentController alloc] init];
     [userController addScriptMessageHandler:self name:@"jssdk"];
     configuration.userContentController = userController;
     self.config = configuration;
     _webview = [[WKWebView alloc] initWithFrame:CGRectZero configuration:self.config];
     _webview.navigationDelegate = self;
     _webview.UIDelegate = self;
  }
  return _webview;
}

- (WKWebViewConfiguration *)config {
  if (_config == nil) {
    _config = [[WKWebViewConfiguration alloc] init];
    _config.userContentController = [[WKUserContentController alloc] init];
    _config.allowsInlineMediaPlayback = YES;        // 允许在线播放
    _config.allowsAirPlayForMediaPlayback = YES;  //允许视频播放
    _config.preferences = [[WKPreferences alloc] init];
    _config.preferences.minimumFontSize = 10;
    _config.preferences.javaScriptEnabled = YES; //是否支持 JavaScript
    _config.processPool = [[WKProcessPool alloc] init];
    NSMutableString *javascript = [NSMutableString string];
    [javascript appendString:@"document.documentElement.style.webkitTouchCallout='none';"];//禁止长按
    [javascript appendString:@"document.documentElement.style.webkitUserSelect='none';"];//禁止选择
    WKUserScript *noneSelectScript = [[WKUserScript alloc] initWithSource:javascript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    [_config.userContentController addUserScript:noneSelectScript];
  }
  return _config;
}
@end
